from pymt import *
import os
import random
from OpenGL.GL import *
import copy
import MTButtonPagesViewer
import MTPageWindow
# import klist as MTList

class MTPagesViewer(MTInnerWindow):

    def __init__(self, kinetics, parent_size, **kwargs):
        print "MTPagesViewer constructed"
        kwargs.setdefault('scale_min', 0.5)
        kwargs.setdefault('scale_max', 2)
        self.parent_size=parent_size
        self.kinetics=kinetics		
        self.height_max = 100
        self.height_min = 100
        self.width_max = self.parent_size[0]
        self.width_min = 300
        super(MTPagesViewer, self).__init__(**kwargs)
		
        self.grow_delta = Vector(0, 0)
        self.aspect_controls_touches = {}		
        self.add_hold_aspect_ratio_controls()
		
		#Add + button
        self.add_button=MTButtonPagesViewer.MTAddButton(filename="resources/graphics/buttonAdd.png", pos=(0,0), size = (50, 50), scale =0.39, cls="",\
		function=self.addPage)
        self.add_widget(self.add_button)
		
		#Create an empty list of pages and a empty list of miniature buttons
        self.pages=[]
        self.miniatures=[]
		
        # self.miniaturesZone=MTMiniaturesZone(fctOpen=self.openPage, fctClose=self.closePage, pos=(110,0), size = (700, 100))
        # self.add_widget(self.miniaturesZone)
        
        # animate the appearance of the window
        self.scale_min_old = self.scale_min
        self.scale_min = 0.01
        self.scale = 0.01
        self.show_window_anim = Animation(duration=0.5, scale = 1, f = "ease_out_elastic")
        @self.show_window_anim.event
        def on_complete(self):
            self.scale_min = self.scale_min_old
        self.do(self.show_window_anim)
        self.is_fullscreen = False

		
    def addPage(self):
		#add a page window
        self.page = MTPageWindow.MTPageWindow(size = (576, 384), pos=(self.x-360, (self.y-580)), rotation=0, function=self.closePage, id=len(self.pages))
        self.kinetics.add_widget(self.page)
		#add the page to the list
        self.pages.append(self.page)
		
        #self.miniaturesZone.addMiniature()
		#if the page is not the first    
        if(len(self.miniatures) > 0):
			#add a miniature button
            miniature_btn=MTButtonPagesViewer.MTMiniature(pos=(110+len(self.miniatures)*110,15),size=(100,70),\
			id=len(self.miniatures), parent=self)			
        else:
			#add the first miniature button		
            miniature_btn=MTButtonPagesViewer.MTMiniature(pos=(110,15), size=(100,70),id=0, parent=self)
		
		#add the miniature to the list
        self.miniatures.append(miniature_btn)       
        self.add_widget(miniature_btn)

	#hide the page with the id, and change the state of the corresponding miniature button
    def	closePage (self,id):
        self.miniatures[id].close()
        self.pages[id].visible=0

	#appear the page with the id
    def	openPage (self,id):
        self.pages[id].visible=1
	
	#prevent the other miniature buttons to move when one miniature button is moving
    def	lockOthers(self, id):
        for mini in self.miniatures:
			if(self.miniatures[id]!=mini):
				mini.lock()
	#unlock the other miniature buttons
    def	unlock(self):
        for mini in self.miniatures:
			mini.unlock()
	
	#move a miniature button to another emplacement
    def moveMiniature(self,id):
        for mini in self.miniatures:
			#if mini is not id		
			if(self.miniatures[id]!=mini):
				#if the miniature(id) is above another miniature
				if(self.miniatures[id].center[0] > mini.x and self.miniatures[id].center[0]  < (mini.x+mini.width) \
				and self.miniatures[id].center[1]  > mini.y and self.miniatures[id].center[1]  < (mini.y+mini.height)):
					#if the miniature(id) go to the left, move the miniature under to the right and switch their emplacements
					if self.miniatures[id]._get_emplacement()-mini._get_emplacement()>0:
						mini.pos=110+(mini._get_emplacement()+1)*110,15
						mini._set_emplacement(mini._get_emplacement()+1)
						self.miniatures[id]._set_emplacement(self.miniatures[id]._get_emplacement()-1)
					#if the miniature(id) go to the right, move the miniature under to the left and switch their emplacements
					else:
						mini.pos=110+(mini._get_emplacement()-1)*110,15
						mini._set_emplacement(mini._get_emplacement()-1)
						self.miniatures[id]._set_emplacement(self.miniatures[id]._get_emplacement()+1)

	# Add the resize control 					
    def add_hold_aspect_ratio_controls(self):
        scaled_border = self.get_scaled_border()
        self.aspect_controls = MTWidget()
        self.add_widget(self.aspect_controls)
        self.aspect_control_top_right = MTImageButton(filename="resources/graphics/aspectControlButtonTextureRoundDots.png", pos=(self.width, self.height), \
		size = (scaled_border, scaled_border), cls="aspect_ratio_controls")
        self.aspect_controls.add_widget(self.aspect_control_top_right)

	# Update the resize control
    def update_aspect_controls(self):
        scaled_border = self.get_scaled_border()
        # hack to lock the window controls to stay the same size when the window is resized
        for child in self.aspect_controls.children:
            child.scale = 1.0 / self.scale # do not scale the aspect controls

        self.aspect_control_top_right.pos = (self.width, self.height)


    def on_touch_down(self, touch):

        # if the touch isn't on the widget we do nothing
        if not self.collide_point(touch.x, touch.y):
            MTInnerWindow.on_touch_down(self, touch)
            return False

        local_touch = self.to_local(touch.x, touch.y)

        if(len(self.aspect_controls_touches.keys()) == 0): # only one touch allowed at a time on the aspect ratio controls
			#if the aspect ratio controls is touched, add it to touches list
            if(self.aspect_control_top_right.collide_point(local_touch[0], local_touch[1])):
                self.aspect_controls_touches[touch.id] = ["top", "right"]

        return MTInnerWindow.on_touch_down(self, touch) # the "return" lets MTInnerWindow deal with the touch

    def on_touch_up(self, touch):
        # if touch in self.aspect_controls_touches then remove it
        if(touch.id in self.aspect_controls_touches.keys()):
            del self.aspect_controls_touches[touch.id]
        return MTInnerWindow.on_touch_up(self, touch)


    def apply_angle_scale_trans(self, angle, scale, trans, point=Vector(0, 0)):
        scale=0
        
        if(len(self.aspect_controls_touches.keys()) >= 1 and len(self.touches) == 1):    # change size rather than scale

            grow_delta = Vector(trans.x, trans.y)
            grow_delta = grow_delta.rotate(360.0 - self.rotation)

            aspect_control_location = self.aspect_controls_touches.items()[0][1]

            # handle switch in direction of growth
            # left
            if("left" in aspect_control_location):
                grow_delta[0] *= -1.0
            # bottom
            if("bottom" in aspect_control_location):
                grow_delta[1] *= -1.0

            # change the size
            self.width += grow_delta[0]
            self.height += grow_delta[1]

            # offset the window
            trans.x = 0
            trans.y = 0
            # left
            if("left" in aspect_control_location):
                trans.x = -grow_delta[0]
            # bottom
            if("bottom" in aspect_control_location):
                trans.y = -grow_delta[1]

            # check that the widget isn't too small or too large
            if(self.height <= self.height_min):
                self.height = self.height_min
            elif(self.height >= self.height_max):
                self.height = self.height_max
            if(self.width <= self.width_min):
                self.width = self.width_min
            elif(self.width >= self.width_max):
                self.width = self.width_max

            # resize the widget's container too
            self.container.height = self.height
            self.container.width = self.width

            scale = 0
            rotate = 0
            
            self.dispatch_event('on_transform', angle, scale, trans, point)
			
        MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)

    def on_transform(self, angle, scale, trans, point):
        self.update_aspect_controls()

    def _get_listPages(self):
		return self.pages
    listPages = property(_get_listPages)
	
    def _get_listMiniatures(self):
		return self.miniatures
    listMiniatures = property(_get_listMiniatures) 	

    def draw(self):
        MTInnerWindow.draw(self)
        self.aspect_controls.dispatch_event('on_draw')

#class for scrolling the miniature
# class MTMiniaturesZone(MTList.MTList):
    # def __init__(self,fctOpen, fctClose, **kwargs):
        # kwargs.setdefault('do_y', False)	
        # super(MTMiniaturesZone, self).__init__(**kwargs)
        # self._current = None
        # self.layout = MTBoxLayout(spacing=10, padding=15)
        # self.add_widget(self.layout)
        # self.fctOpen=fctOpen
        # self.fctClose=fctClose
        # self.miniatures=[]
        
    # def addMiniature(self):		
        #if the page is not the first    
        # if(len(self.miniatures) > 0):
            # miniature_btn=MTButtonPagesViewer.MTMiniature(pos=(110+len(self.miniatures)*110,15),size=(100,70),\
			# id=len(self.miniatures), parent=self)		
            
        # else:
            # miniature_btn=MTButtonPagesViewer.MTMiniature(pos=(110,15), size=(100,70),id=0, parent=self)	
        # @miniature_btn.event
        # def on_press(touch):
            # print "press miniature_btn"
			
        # self.miniatures.append(miniature_btn)        
        # self.layout.add_widget(miniature_btn)
        # self.layout.do_layout()
	
    # def on_touch_down(self, touch):
        # ret = super(MTMiniaturesZone, self).on_touch_down(touch)
        # if self.collide_point(*touch.pos):
            # return True
        # return ret

    # def on_touch_move(self, touch):
        # ret = super(MTMiniaturesZone, self).on_touch_move(touch)
        # if self.collide_point(*touch.pos):
            # return True
        # return ret

    # def on_touch_up(self, touch):
        # ret = super(MTMiniaturesZone, self).on_touch_up(touch)
        # if self.collide_point(*touch.pos):
            # return True
        # return ret
	
    # def close(self,id):
        # self.miniatures[id].close()
	
    # def draw(self):
        # MTList.MTList.draw(self)